package org.jupiter.blog.redis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

@Configuration
public class RedisConfig {

	/**
	 * 使用 JDK 序列化的 RedisTemplate
	 */
	@Bean(name = "jdkRedisTemplate")
	public RedisTemplate<String, Object> jdkRedisTemplate(RedisConnectionFactory factory) {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(factory);

		// key 用 String 序列化
		StringRedisSerializer stringSerializer = new StringRedisSerializer();

		// value 用 JDK 序列化
		JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer();

		template.setKeySerializer(stringSerializer);
		template.setHashKeySerializer(stringSerializer);

		template.setValueSerializer(jdkSerializer);
		template.setHashValueSerializer(jdkSerializer);

		template.afterPropertiesSet();
		return template;
	}

	/**
	 * 使用 JSON 序列化的 RedisTemplate
	 */
	@Bean(name = "jsonRedisTemplate")
	public RedisTemplate<String, Object> jsonRedisTemplate(RedisConnectionFactory factory) {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(factory);

		// key 序列化
		StringRedisSerializer stringSerializer = new StringRedisSerializer();

		// value 序列化
		GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();

		template.setKeySerializer(stringSerializer);
		template.setHashKeySerializer(stringSerializer);
		template.setValueSerializer(valueSerializer);
		template.setHashValueSerializer(valueSerializer);

		template.afterPropertiesSet();
		return template;
	}

	/**
	 * 默认 RedisTemplate（推荐 JSON 版本）
	 */
	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
		return jsonRedisTemplate(factory);
	}

}

